package 力扣面试经典150;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2024-03-23
 * Time:10:52
 */

import java.util.Arrays;

/**
 * 力扣面试经典150:106. 从中序与后序遍历序列构造二叉树
 * 已解答
 * 中等
 * 相关标签
 * 相关企业
 * 给定两个整数数组 inorder 和 postorder ，其中 inorder 是二叉树的中序遍历， postorder 是同一棵树的后序遍历，请你构造并返回这颗 二叉树 。
 * 示例 1:
 * 输入：inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
 * 输出：[3,9,20,null,null,15,7]
 */
public class buildTreeⅡ {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return dfs(inorder, postorder, postorder.length - 1, 0, inorder.length - 1);
    }

    TreeNode dfs(int[] inorder, int[] postorder, int postmid, int inleft, int inright) {
        if (inleft > inright) return null;

        int val = postorder[postmid];
        TreeNode node = new TreeNode(val);

        int inmid = -1;
        for (int i = inleft; i <= inright; i++) {
            if (inorder[i] == val) {
                inmid = i;
                break;
            }
        }

        node.left = dfs(inorder, postorder, postmid - (inright - inmid) - 1, inleft, inmid - 1);
        node.right = dfs(inorder, postorder, postmid - 1, inmid + 1, inright);

        return node;
    }

}
